import React, { useState, useRef, useImperativeHandle } from "react";

import { Spin, Modal, notification } from 'antd'
import {FCForm} from "@components";
import { session } from '@core'

const ModalComponent = (props) => {
  const {
    modalRef,
    modalFormProps,
    addApi,
    updataId,
    updataApi,
    queryFormRef
  } = props

  const [open, setOpen] = useState(false)
  const [title, setTitle] = useState('')
  const [loading, setLoading] = useState(false)

  // 暴露给父组件的方法
  useImperativeHandle(modalRef, () => ({
    showModal: (data, title) => {
      setOpen(true)
      if (!data) {
        session.remove('modalId')
        return setTitle(title || '新增')
      }
      setTitle(title || '编辑')
      session.set('modalId',data[updataId]) // 存储id, 后续提交表单需要用到
      setTimeout(() => {
        formRef.current?.setFieldsValue?.({...data})
      }, 0);
    },
    setModalLoading: (ModalLoading) => setLoading(ModalLoading),
  }))

  const defaultFormRef = useRef("modalForm")
  const { formRef=defaultFormRef } = modalFormProps;
  const formProps = {
    name:"modalForm",
    formRef,
    onFinish: async (v) => {
      setLoading(true)
      const modalId = session.get('modalId')
      const params = {...v}
      let fetchData = addApi
      if (modalId) {
        params[updataId] = modalId
        fetchData = updataApi
      }

      const { data, error } = await fetchData(params)
      setLoading(false)
      if (error) return

      notification.success({message:data});
      setOpen(false)
      queryFormRef.current?.submit?.() // 重新加载表格的数据
    },
    layoutProps: {
      layout: "horizonal",
      // labelCol: {span: 6},
      // wrapperCol: {span: 16},
    },
    ...modalFormProps
  };

  const handleOk = () => {
    formRef.current?.submit?.()
  };

  const handleCancel = () => {
    if (loading) return
    setOpen(false)
  };

  return (
    <Modal
      title={title}
      className='modal'
      open={open}
      onOk={handleOk}
      bodyStyle={{padding: '24px 24px 0', maxHeight: '680px', overflow: 'hidden'}}
      onCancel={handleCancel}
      maskClosable= {false}
      destroyOnClose={true}
      confirmLoading={loading}
    >
      <Spin spinning={loading}>
        <FCForm {...formProps}/>
      </Spin>
    </Modal>
  );
};

export default React.memo(ModalComponent);
